/*
** env1.c for 42sh in /home/guina_b/
** 
** Made by benoit guina
** Login   <guina_b@epitech.net>
** 
** Started on  Fri Jan 01 00:00:00 2010 benoit guina
** Last update Fri Jan 01 00:00:00 2010 benoit guina
*/

#include <stdlib.h>
#include <string.h>
#include "alloc.h"
#include "env.h"

char **env_get_var(t_env *env, char *var)
{
  int l;
  unsigned int i;

  l = -1;
  while (var[++l] && var[l] != '=');
  i = -1;
  while (++i < env->len)
    if (!strncmp(var, env->data[i], l) && env->data[i][l] == '=')
      return (&env->data[i]);
  return (0);
}

char *env_get_var_value(t_env *env, char *var)
{
  char **var_found;
  int l;

  if ((var_found = env_get_var(env, var)))
  {
    l = -1;
    while ((*var_found)[++l] && (*var_found)[l] != '=');
    if ((*var_found)[l])
      l++;
    return (*var_found + l);
  }
  return (0);
}

static int env_add_var(t_env *env, char *var)
{
  int previous_alloc_size;
  char *new_var;
  char **new_data;

  if (!(new_var = xmalloc(strlen(var) + 1, __FILE__, __LINE__)))
    return (-1);
  strcpy(new_var, var);
  if (env->alloc_size == env->len + 1)
  {
    previous_alloc_size = env->alloc_size;
    env->alloc_size += env->len / 3 + 5;
    if ((new_data = env_copy_data(env->data, &env->alloc_size)))
    {
      env_free_data(env->data);
      env->data = new_data;
    }
    else
    {
      env->alloc_size = previous_alloc_size;
      xfree(new_var);
      return (-1);
    }
  }
  env->data[env->len++] = new_var;
  return (0);
}

int env_set_var(t_env *env, char *var)
{
  char **d;
  char *new_var;
  unsigned int l;

  if (!(d = env_get_var(env, var)))
    return (env_add_var(env, var));
  if (strlen(*d) > (l = strlen(var)))
  {
    if ((new_var = xmalloc(l + 1, __FILE__, __LINE__)))
    {
      strcpy(new_var, var);
      xfree(*d);
      *d = new_var;
      return (0);
    }
    return (-1);
  }
  strcpy(*d, var);
  return (0);
}

int env_unset_var(t_env *env, char *var)
{
  char **d;
  char **p;

  if ((d = env_get_var(env, var)))
  {
    p = d;
    while (p[1])
      p++;
    xfree(*d);
    *d = *p;
    *p = 0;
    env->len--;
    return (0);
  }
  return (-1);
}
